class_name DotDamageArea
extends Marker2D

@onready var dot_damage_area: Area2D = $DotDamageArea
@onready var collision_shape_2d: CollisionShape2D = $DotDamageArea/CollisionShape2D

@export var hit_interval: float = 2.0
@export var attack: float = 1
@export var knockback: float = 20
@export var width: int = 0
@export var height: int = 0

var hit_targets: Dictionary[Node2D, float] = {}
var level: Level = null


func _ready() -> void:
	level = get_tree().current_scene as Level
	collision_shape_2d.shape = collision_shape_2d.shape.duplicate()
	init_collision()


func init_collision():
	var shape = collision_shape_2d.shape as RectangleShape2D
	shape.size = Vector2(width, height)
	collision_shape_2d.position = shape.size / 2.0


func _physics_process(delta: float) -> void:
	process_hit(delta)
		

func disable_physics():
	collision_shape_2d.disabled = true
	

func enable_physics():
	collision_shape_2d.disabled = false
	

func process_hit(delta):
	if hit_targets.keys().size() <= 0: return
	
	for hit_target in hit_targets.keys():
		if not is_instance_valid(hit_target): continue
		
		hit_targets[hit_target] -= delta
		
		if hit_targets[hit_target] <= 0:
			var hit_data = create_hit_data()
			hit_target.take_hit(hit_data)
			
			hit_targets[hit_target] = hit_interval
			

func create_hit_data():
	var hit_data = HitData.new()
	hit_data.attack = attack
	hit_data.is_critical = false
	hit_data.knockback = knockback
	return hit_data


func _on_dot_damage_area_area_entered(area: Area2D) -> void:
	var source = area.source
	if source != null and is_instance_valid(source):
		hit_targets[source] = hit_interval


func _on_dot_damage_area_area_exited(area: Area2D) -> void:
	var source = area.source
	if source in hit_targets:
		hit_targets.erase(source)
